/** 注释
 * @Name infiniteScroll;
 * @Author FiveXu
 * @Description infiniteScroll
 * @Date 2021-07-26 09:36
 */
import { App, DirectiveBinding } from 'vue'

interface InfiniteScrollEl extends HTMLElement {
  oldScrollHeight: number
}

const handleScroll = (el?: InfiniteScrollEl, bind?: DirectiveBinding): () => void => {
  return () => {
    if (!el || !bind) return
    el.oldScrollHeight = 0
    const disScroll = el.scrollHeight - el.scrollTop - el.clientHeight
    const disabled = el.getAttribute('infinite-scroll-disabled') === 'true'
    if (disScroll <= 0 && el.oldScrollHeight !== el.scrollHeight) {
      el.oldScrollHeight = el.scrollHeight
      if (!disabled) bind.value()
    }
  }
}

const initInfiniteScroll = (app: App): void => {
  app.directive('infinite-scroll', {
    mounted (el: InfiniteScrollEl, bind: DirectiveBinding) {
      el.addEventListener('scroll', handleScroll(el, bind))
    },
    unmounted (el: InfiniteScrollEl) {
      el.removeEventListener('scroll', handleScroll())
    }
  })
}

export default initInfiniteScroll
